package com.xzz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xzz.domain.KillActivity;
import com.xzz.domain.KillCourse;
import com.xzz.mapper.KillActivityMapper;
import com.xzz.service.IKillActivityService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xzz.service.IKillCourseService;
import com.xzz.util.AssertUtil;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xzz
 * @since 2022-09-21
 */
@Service
public class KillActivityServiceImpl extends ServiceImpl<KillActivityMapper, KillActivity> implements IKillActivityService {

    @Autowired
    private IKillCourseService killCourseService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void publish(Long activityId) {
        //校验
        KillActivity killActivity = selectById(activityId);
        AssertUtil.isNotNull(killActivity,"活动不存在");
        Date date = new Date();
        AssertUtil.isTrue(date.before(killActivity.getEndTime()),"活动时间不合理");
        EntityWrapper<KillCourse> wrapper = new EntityWrapper<>();
        wrapper.eq("activity_id",killActivity.getId());
        List<KillCourse> killCourses = killCourseService.selectList(wrapper);
        AssertUtil.isNotNull(killCourses,"没有秒杀课程");

        //修改活动状态和时间
        killActivity.setPublishStatus(KillActivity.STATE_PUBLISH);
        killActivity.setPublishTime(date);
        updateById(killActivity);

        //活动商品存到Redis里面，通过Redis的hash里面的大小key保存
        for (KillCourse killCourse : killCourses) {
            //每个商品的库存使用信号量存储到Redis
            String xiaoKey = killCourse.getId().toString();
            //获得信号量
            RSemaphore semaphore = redissonClient.getSemaphore(xiaoKey);
            //信号量不能为负数，无法设置许可
            boolean trySetPermits = semaphore.trySetPermits(killCourse.getKillCount());
            if (!trySetPermits){
                continue;
            }
            //可以通过大K找到包含小k和全部数据
            String daKey = "avtivity:"+killActivity.getId();
            redisTemplate.opsForHash().put(daKey,xiaoKey, killCourse);

        }
    }
}
